//
//  ViewController.swift
//  SwiftWKWebViewTest
//
//  Created by 王冲 on 2019/12/8.
//  Copyright © 2019 王冲. All rights reserved.
//

import UIKit
import WebKit
class ViewController: UIViewController {
    
    /// 声明WKWebView属性
    var wkWebView: WKWebView?
    /// 声明UIProgressView属性
    var progressView: UIProgressView?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        self.view.backgroundColor = UIColor.green
        
        // 创建网页配置
        let configuration = WKWebViewConfiguration()
        // 对网页视图进行实例化
        wkWebView = WKWebView(frame: self.view.frame, configuration: configuration)
        wkWebView?.navigationDelegate = self
        self.view.addSubview(wkWebView!)
        
        let url = URL(string: "http://www.baidu.com")
        let request = URLRequest(url: url!)
        
        wkWebView!.load(request)

        // 创建进度条 UIProgressView
        progressView = UIProgressView(frame: CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: 10))
        progressView?.progressTintColor = UIColor.green
        progressView?.progress = 0
        self.view.addSubview(progressView!)
        
        // 对 wkWebView 实例的 estimatedProgress 属性进行监听
        wkWebView?.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)

    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == "estimatedProgress" {
            progressView?.progress = Float(wkWebView!.estimatedProgress)
            print(progressView?.progress as Any)
        }
    }


    func wkSet() -> () {
        
        // 创建网页配置
        let configuration = WKWebViewConfiguration()
        // 配置进程池
        let processPool = WKProcessPool()
        configuration.processPool = processPool
        
        // 偏好配置
        let preferences = WKPreferences()
        // 设置网页页面的最小字号
        preferences.minimumFontSize = 0
        // 设置是否支持 javaScript 脚本 默认为true
        preferences.javaScriptEnabled = true
        // 设置是否允许不经过用户交互由 javaScript 代码自动打开窗口
        preferences.javaScriptCanOpenWindowsAutomatically = true
        
        configuration.preferences = preferences
        
        
        // 进行原生与 JavaScript 交互配置
        let userContentController = WKUserContentController()
        // 设置代理并且注册要被 JavaScript 代码调用的原生方法名称
        userContentController.add(self, name: "nativeFunc")
        // 向网页注入一段 JavaScript 代码
        let javaScriptString = "function userFunc() { window.webkit.messageHandlers.nativeFunc.postMessage ({\"班级\":\"WC\"}) };userFunc()"
        let userScript = WKUserScript(source: javaScriptString, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
        // 进行注入
        userContentController.addUserScript(userScript)
        
        configuration.userContentController = userContentController
        
        
        
        
    }

}

extension ViewController: WKScriptMessageHandler {
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }
}

extension ViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        print("加载完成")
        progressView?.isHidden = true
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print("加载失败")
    }
}
